package cb.com.etcdemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cb.com.etcdemo.API.API;
import cb.com.etcdemo.adapter.OnlineAdapter;
import cb.com.etcdemo.bean.DeviceState;
import cb.com.etcdemo.bean.DeviceStateOnLine;
import cb.com.etcdemo.http.Okhttp;
import cb.com.etcdemo.util.Tools;
import cb.com.etcdemo.view.XListView;
import cb.com.etcdemohgz.R;

/**
 * 在线
 */

public class OnLineFragment extends Base_Fragment implements XListView.IXListViewListener {

    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.tv_page_add)
    TextView tvPageAdd;
    @BindView(R.id.rl_page_title)
    RelativeLayout rlPageTitle;
    @BindView(R.id.et_completed_search)
    EditText etCompletedSearch;
    @BindView(R.id.iv_completed_search)
    ImageView ivCompletedSearch;
    @BindView(R.id.ll_complete_searxh)
    LinearLayout llCompleteSearxh;
    @BindView(R.id.xlv_completed)
    XListView xlvCompleted;
    @BindView(R.id.Fla_search_FDStationinfo)
    FloatingActionButton FlaSearchFDStationinfo;
    @BindView(R.id.ll_complete_nodata)
    LinearLayout llCompleteNodata;
    private Unbinder unbinder;
    private static final String PAGE_NAME_KEY = "PAGE_NAME_KEY";
    private int currentPage = 1;
    private int pageSize = 20;
    private String queryCriteria = "";

    private List<DeviceStateOnLine.ListBean> stationInfos = new ArrayList<>();
    // 当前页
    private Handler handler = new Handler();
    // 公共对象
    private DeviceStateOnLine page;
    // 适配器
    private OnlineAdapter adapter;


    @OnClick(R.id.iv_completed_search)
    public void toSearch() {
        queryCriteria = etCompletedSearch.getText().toString();
//        if (TextUtils.isEmpty(queryCriteria)) {
//            Tools.showMsg(getActivity(), "搜索内容不能为空");
//            return;
//        }
        stationInfos.clear();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        findApiResourceAccountStationByPage();
    }

    public static OnLineFragment getInstance(String pageName) {
        Bundle args = new Bundle();
        args.putString(PAGE_NAME_KEY, pageName);
        OnLineFragment pageFragment = new OnLineFragment();
        pageFragment.setArguments(args);
        return pageFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container, false);
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, view);
        xlvCompleted.setPullRefreshEnable(false);
        xlvCompleted.setPullLoadEnable(false);
        xlvCompleted.setXListViewListener(this);
        etCompletedSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int count) {
                Log.e("8888", "xx"+count);

            }

            @Override
            public void afterTextChanged(Editable editable) {


            }
        });
        llCompleteNodata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryCriteria="";
                findApiResourceAccountStationByPage();
            }
        });

        xlvCompleted.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("888", "xx"+i);
                DeviceStateOnLine.ListBean listBean = adapter.getInfos().get(i-1);
                Intent intent = new Intent(getActivity(), WeiXiuFanKuiActivity.class);
                Intent intent1 = intent.putExtra("listBean", listBean);
                startActivity(intent1);

            }
        });

        return view;
    }

    /**
     * 判断是否是初始化Fragment
     */
    private boolean hasStarted = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            if (hasStarted) {
                xlvCompleted.setPullRefreshEnable(false);
                xlvCompleted.setPullLoadEnable(false);
                queryCriteria = "";
                stationInfos.clear();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                findApiResourceAccountStationByPage();
            }
        } else {
            if (hasStarted) {
                hasStarted = false;
            }
        }
    }

    @Override
    public void lazyLoad() {

    }

    @Override
    public void onResume() {
        super.onResume();
        hasStarted = true;
        setUserVisibleHint(true);
    }

    private void findApiResourceAccountStationByPage() {
        stationInfos.clear();
        try {
            showdialog();
            Okhttp.get(API.Base+"/web/deviceState/listDeviceStateOnLine?currentPage="+"1"+"&type=1&queryCriteria="+queryCriteria,null,new Okhttp.Objectcallback() {
                @Override
                public void onsuccess(String st) {
                    try {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Log.e("androidN在线","在线JSON:"+ st);
                        Log.e("androidAPI", "在线API:"+API.Base+"/web/deviceState/listDeviceStateOnLineByPage?currentPage="+"1"+"&type=1&queryCriteria="+queryCriteria);
                        // 把JSON转换为PageUtils对象
                        page = JSON.parseObject(st,
                                DeviceStateOnLine.class);
                        if (page.getList() != null) {
                            // 把Page里的集合转换为用车申请泛型集合
                            stationInfos = page.getList();
                            if (stationInfos.size() > 0) {
                                Log.e("androidN在线size","size:"+ stationInfos.size());
                                ResourceActivity.mBadgeCountList.clear();
                                ResourceActivity.mBadgeCountList.add(page.getOnLineCount());
                                ResourceActivity.mBadgeCountList.add(page.getOffLineCount());
                                ResourceActivity.mBadgeCountList.add(page.getNotOnLine());
                                ResourceActivity.mHandler.sendEmptyMessage(200);
                                xlvCompleted
                                        .setVisibility(View.VISIBLE);
                                llCompleteSearxh.setVisibility(View.VISIBLE);
                                llCompleteNodata
                                        .setVisibility(View.GONE);
                                // 如数据大于19则显示允许加载更多
                                xlvCompleted
                                        .setPullRefreshEnable(true);
                                adapter = new OnlineAdapter(
                                        getActivity(),
                                        stationInfos);
                                xlvCompleted.setAdapter(adapter);
                            } else {
                                xlvCompleted
                                        .setVisibility(View.GONE);
//                                llCompleteSearxh.setVisibility(View.GONE);
                                llCompleteNodata
                                        .setVisibility(View.VISIBLE);
                                adapter = null;
                                xlvCompleted
                                        .setPullRefreshEnable(false);
                                xlvCompleted
                                        .setPullLoadEnable(false);
                            }
                        } else {
                            Tools.showMsg(getActivity(),
                                    "当前网络繁忙！");
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        Tools.showMsg(getActivity(), "当前网络繁忙！");
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFalia(int code, String errst) {
                    if (dialog!=null) {
                        dialog.dismiss();
                    }

                    Toast.makeText(getActivity(), "网络错误，请检查网络！" + errst, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    KProgressHUD dialog;

    private void showdialog() {
        if (null == dialog) {
            dialog = KProgressHUD.create(getActivity())
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel("正在加载中，请稍候")
                    .setCancellable(true)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f);
        }
        dialog.show();
    }

    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    // 停止刷新或加载并记录更新时间
    private void onLoad() {
        xlvCompleted.stopRefresh();
        xlvCompleted.stopLoadMore();
        // 获取系统的时间
        Calendar car = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        SimpleDateFormat mat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String format = mat.format(car.getTime());
        xlvCompleted.setRefreshTime(format);
    }

    //
    // 下拉刷新时调用
    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                queryCriteria="";
                currentPage = 1;
                // 重新赋值
                findApiResourceAccountStationByPage();
                onLoad();
            }
        }, 2000);
    }


    // 加载更多时调用
    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub

        currentPage++;
        findApiResourceAccountStationByPage();
    }
}
